<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-bar-left" @click="handleBack">
        <uni-icons type="left" size="20" color="#333"/>
      </view>
      <view class="nav-bar-title">
        {{deptSubNameText}}
      </view>
      <view class="nav-bar-right">
        <uni-icons type="more" size="20" color="#333"/>
      </view>
    </view>

    <!-- 日历部分 -->
    <view class="calendar">
      <view class="week-row">
        <text v-for="(day, index) in weekDays" :key="index" class="week-item">{{ day }}</text>
      </view>
      <view class="date-row">
        <view 
          v-for="(date, index) in dates" 
          :key="index"
          :class="['date-item', { active: selectedDate === date.fullDate }]"
          @click="selectDate(date)"
        >
          <text class="day">{{ date.day }}</text>
          <text :class="['status', { 'status-available': date.status === '有号', 'status-unavailable': date.status === '无号' }]">
            {{ date.status }}
          </text>
        </view>
      </view>
    </view>

    <!-- 医生信息 -->
    <view class="doctor-list" v-if="doctorList && doctorList.length > 0">
      <!-- 医生列表标题 -->
      <view class="doctor-list-title">
        <text>出诊医生 ({{ doctorList.length }})</text>
      </view>
      
      <!-- 医生列表项 -->
      <view class="doctor-item" 
        v-for="(doctor, index) in doctorList" 
        :key="doctor.id"
        :class="{'selected': selectedDoctor && selectedDoctor.id === doctor.id}"
        @click="selectDoctor(doctor)">
        <view class="doctor-header">
          <image class="avatar" :src="doctor.photo" mode="aspectFill" />
          <view class="info">
            <view class="name-title">
              <text class="name">{{ doctor.name }}</text>
              <text class="title">{{ doctor.job }}</text>
            </view>
            <view class="stats">
              <text class="total">总量：{{ doctor.maximum }}</text>
              <text class="price">¥{{ doctor.price }}</text>
            </view>
          </view>
          <view class="num-info">
            <text :class="['num', {'full': doctor.maximum <= doctor.num, 'available': doctor.maximum > doctor.num}]">
              剩余：{{ doctor.maximum - doctor.num }}
            </text>
          </view>
        </view>
        
        <!-- 如果是选中的医生，显示详细描述 -->
        <view class="doctor-detail" v-if="selectedDoctor && selectedDoctor.id === doctor.id">
          <text class="specialty">{{ doctor.description }}</text>
          <button class="book-btn" :disabled="doctor.maximum <= doctor.num" @click.stop="handleBook">
            {{ doctor.maximum > doctor.num ? '预约挂号' : '已约满' }}
          </button>
        </view>
      </view>
    </view>

    <view class="no-doctor" v-else>
      <text>暂无医生出诊</text>
    </view>
  </view>
</template>

<script>
import { apiBaseUrl } from '../../../config/api'

export default {
  data() {
    return {
      deptSubId: '',
      deptSubNameText: '诊室名称',
      selectedDate: '',
      dates: [],
      weekDays: [],
      selectedDoctor: null,
      doctorList: []
    }
  },
  
  onLoad(options) {
    console.log('页面参数:', options)
    
    if (options && options.deptSubId && options.deptSubName) {
      this.deptSubId = options.deptSubId
      try {
        const decodedName = decodeURIComponent(options.deptSubName)
        console.log('解码后的诊室名称:', decodedName)
        this.deptSubNameText = decodedName
      } catch(e) {
        console.error('解码诊室名称失败:', e)
        this.deptSubNameText = options.deptName
      }
    } else {
      uni.showToast({
        title: '缺少必要参数',
        icon: 'none'
      })
    }
    
    // 生成日期数据
    this.generateDates()
  },
  
  methods: {
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 生成日期数据
    generateDates() {
      const dates = []
      const today = new Date()
      const weekDayNames = ['日', '一', '二', '三', '四', '五', '六']
      const weekDaysFormatted = []
      
      // 生成连续7天的日期
      for (let i = 0; i < 7; i++) {
        const date = new Date(today)
        date.setDate(today.getDate() + i)
        
        // 获取星期几并添加到weekDaysFormatted数组
        const weekIndex = date.getDay() // 0是周日，1是周一...
        weekDaysFormatted.push(weekDayNames[weekIndex])
        
        dates.push({
          day: date.getDate(),
          fullDate: this.formatDate(date),
          status: '无号',
          rawStatus: '',
          weekDay: weekIndex
        })
      }
      
      // 设置星期数组
      this.weekDays = weekDaysFormatted
      this.dates = dates
      
      if (dates.length > 0) {
        this.selectedDate = dates[0].fullDate
      }
      
      // 获取排班信息
      this.getScheduleInfo()
    },
    
    // 获取排班信息
    getScheduleInfo() {
      try {
        const today = new Date()
        const endDate = new Date(today)
        endDate.setDate(today.getDate() + 6)
        
        const requestData = {
          deptSubId: this.deptSubId,
          startDate: this.formatDate(today),
          endDate: this.formatDate(endDate)
        }
        
        console.log('请求排班数据:', requestData)
        
        // 使用Promise方式调用
        uni.request({
          url: apiBaseUrl + '/doctor/schedule/selectDoctorScheduleBySubIdAndDate',
          method: 'POST',
          data: requestData,
          success: (res) => {
            console.log('排班信息返回:', res)
            
            if (res.data && res.data.code === 200) {
              const schedules = res.data.result || []
              
              // 更新日期状态
              this.updateDatesStatus(schedules)
            } else {
              console.error('请求返回异常:', res)
            }
          },
          fail: (err) => {
            console.error('请求发生错误:', err)
          }
        })
      } catch (error) {
        console.error('获取排班信息失败:', error)
      }
    },
    
    // 更新日期状态
    updateDatesStatus(schedules) {
      // 遍历日期列表
      this.dates = this.dates.map(date => {
        // 查找对应日期的排班
        const schedule = schedules.find(s => s.date === date.fullDate)
        
        // 设置状态
        if (schedule && schedule.status === '出诊') {
          date.status = '有号'
          date.rawStatus = schedule.status
        } else if (schedule && schedule.status) {
          date.status = schedule.status
          date.rawStatus = schedule.status
        }
        
        return date
      })
      
      // 获取第一天的医生信息
      if (this.dates.length > 0 && this.dates[0].rawStatus === '出诊') {
        this.getDoctorInfo(this.dates[0].fullDate)
      }
    },
    
    // 获取医生信息
    getDoctorInfo(date) {
      try {
        uni.request({
          url: apiBaseUrl + '/doctor/schedule/selectDoctorShiftDetailsBySubIdAndDate',
          method: 'POST',
          data: {
            deptSubId: this.deptSubId,
            date: date
          },
          success: (res) => {
            if (res.data && res.data.code === 200) {
              this.doctorList = res.data.result || [];
              this.selectedDoctor = this.doctorList.length > 0 ? this.doctorList[0] : null;
              console.log('获取到医生列表:', this.doctorList);
            } else {
              console.error('请求返回异常:', res)
            }
          },
          fail: (err) => {
            console.error('请求发生错误:', err)
          }
        })
      } catch (error) {
        console.error('获取医生信息失败:', error)
      }
    },
    
    // 选择日期
    selectDate(date) {
      this.selectedDate = date.fullDate
      
      if (date.rawStatus === '出诊') {
        // 保存当前选中的医生ID，以便在获取新医生列表后恢复选择
        const currentDoctorId = this.selectedDoctor ? this.selectedDoctor.id : null;
        
        // 获取医生列表
        this.getDoctorInfo(date.fullDate)
        
        // 如果有医生列表并且有选中医生，在获取新列表后尝试保持选中状态
        if (currentDoctorId) {
          setTimeout(() => {
            const doctor = this.doctorList.find(d => d.id === currentDoctorId);
            if (doctor) {
              this.selectDoctor(doctor);
            }
          }, 300);
        }
      } else {
        this.doctorList = [];
        this.selectedDoctor = null;
      }
    },
    
    // 选择医生
    selectDoctor(doctor) {
      // 如果医生没有剩余号源，显示提示但仍然允许选择查看详情
      if (doctor.maximum <= doctor.num) {
        uni.showToast({
          title: '该医生当日号源已约满',
          icon: 'none'
        });
      }
      this.selectedDoctor = doctor;
    },
    
    // 挂号
    handleBook() {
      if (!this.selectedDoctor) {
        uni.showToast({
          title: '请选择医生',
          icon: 'none'
        })
        return
      }
      
      // 再次检查号源是否充足
      if (this.selectedDoctor.maximum <= this.selectedDoctor.num) {
        uni.showToast({
          title: '该医生当日号源已约满',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/index/Make-appointment/select-time?doctorId=${this.selectedDoctor.id}&date=${this.selectedDate}&deptSubId=${this.deptSubId}`
      })
    },
    
    // 返回
    handleBack() {
      const pages = getCurrentPages()
      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f8ff;
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 90rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  z-index: 100;
  padding-top: 44px; /* 状态栏高度 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  
  .nav-bar-left {
    width: 80rpx;
    height: 90rpx;
    display: flex;
    align-items: center;
  }
  
  .nav-bar-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
  }
  
  .nav-bar-right {
    width: 80rpx;
    height: 90rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}

.calendar {
  margin: 24rpx;
  margin-top: calc(44px + 90rpx + 24rpx); /* 状态栏 + 导航栏 + 间距 */
  background: #fff;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .week-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
    
    .week-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .date-row {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    
    .date-item {
      width: calc(100% / 7);
      height: 120rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: relative;
      
      .day {
        font-size: 32rpx;
        color: #333;
        width: 60rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        margin-bottom: 8rpx;
      }
      
      .status {
        font-size: 24rpx;
        color: #999;
        padding: 4rpx 8rpx;
        border-radius: 4rpx;
        
        &.status-available {
          color: #2979ff;
          background-color: rgba(41, 121, 255, 0.1);
        }
        
        &.status-unavailable {
          color: #999;
          background-color: #f5f5f5;
        }
      }
      
      &.active {
        .day {
          color: #fff;
          background: #2979ff;
          border-radius: 50%;
        }
        
        .status {
          color: #2979ff;
          
          &.status-available {
            background-color: rgba(41, 121, 255, 0.2);
          }
        }
      }
    }
  }
}

.doctor-list {
  margin: 24rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .doctor-list-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
    padding: 0 10rpx;
  }
  
  .doctor-item {
    padding: 20rpx;
    border-radius: 8rpx;
    margin-bottom: 16rpx;
    border: 1px solid #f0f0f0;
    transition: all 0.3s ease;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.selected {
      border-color: #2979ff;
      background-color: rgba(41, 121, 255, 0.05);
    }
    
    .doctor-header {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .avatar {
        width: 120rpx;
        height: 120rpx;
        border-radius: 60rpx;
        border: 1px solid #f0f0f0;
      }
      
      .info {
        flex: 1;
        
        .name-title {
          margin-bottom: 10rpx;
          
          .name {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            margin-right: 12rpx;
          }
          
          .title {
            font-size: 24rpx;
            color: #666;
            background: #f5f5f5;
            padding: 2rpx 10rpx;
            border-radius: 4rpx;
          }
        }
        
        .stats {
          font-size: 26rpx;
          
          .total {
            color: #666;
            margin-right: 20rpx;
          }
          
          .price {
            color: #f56c6c;
            font-weight: 500;
          }
        }
      }
      
      .num-info {
        font-size: 26rpx;
        background: #f8f8f8;
        padding: 4rpx 12rpx;
        border-radius: 4rpx;
        
        .num {
          color: #666;
          &.full {
            color: #f56c6c;
          }
          &.available {
            color: #07c160;
          }
        }
      }
    }
    
    .doctor-detail {
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 1px dashed #eee;
      display: flex;
      flex-direction: column;
      
      .specialty {
        font-size: 26rpx;
        color: #666;
        line-height: 1.6;
        margin-bottom: 20rpx;
      }
      
      .book-btn {
        align-self: flex-end;
        width: 180rpx;
        height: 70rpx;
        line-height: 70rpx;
        background: linear-gradient(135deg, #2979ff, #1a56ff);
        color: #fff;
        font-size: 28rpx;
        font-weight: 500;
        border-radius: 35rpx;
        text-align: center;
        box-shadow: 0 4rpx 10rpx rgba(41, 121, 255, 0.3);
        transition: all 0.3s ease;
        
        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 2rpx 6rpx rgba(41, 121, 255, 0.3);
        }
      }
    }
  }
}

.no-doctor {
  margin: 24rpx;
  padding: 40rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
</style> 